import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '_views/Home'
import { isLogin } from '_utils'
Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '/home',
    name: '首页',
    meta: {
      needLogin: false,
      needalive: true
    },
    component: Home
  },
  {
    path: '/cart',
    name: '购物车',
    meta: {
      needLogin: true
    },
    component: () => import('_views/Cart')
  },
  {
    path: '/cate',
    name: '分类',
    meta: {
      needLogin: false
    },
    component: () => import('_views/Cate')
  },
  {
    path: '/user',
    name: '个人中心',
    meta: {
      needLogin: false
    },
    component: () => import('_views/User')
  },
  {
    path: '/detail/:id',
    name: '详情页',
    meta: {
      needLogin: true,
    },
    component: () => import('_views/Detail')
  },
  {
    path: '/itemlists',
    name: '商品列表',
    meta: {
      needLogin: false
    },
    component: () => import('_views/ItemLlists')
  },
  {
    path: '/login',
    name: '登录',
    meta: {
      needLogin: false
    },
    component: () => import('_views/Login')
  },
  {
    path: '/register',
    name: '注册',
    meta: {
      needLogin: false
    },
    component: () => import('_views/Register')
  }
  ,{
    path: '/order',
    name: '订单页',
    meta: {
      needLogin: false
    },
    component: () => import('_views/Order')
  },
  {
    path: '/contentadd',
    name: '增加联系人',
    meta: {
      needLogin: false
    },
    component: () => import('_views/ContentAdd')
  },
  {
    path: '/contentlists',
    name: '联系人列表',
    meta: {
      needLogin: false
    },
    component: () => import('_views/ContentLists')
  },
  {
    path: '/contentUpdate',
    name: '修改联系人',
    meta: {
      needLogin: false
    },
    component: () => import('_views/ContentUpdate')
  },
  {
    path: '/search',
    name: '搜索',
    meta: {
      needLogin: false
    },
    component: () => import('_views/Search')
  },
  {
    path: '/searchlists',
    name: '搜索列表',
    meta: {
      needLogin: false
    },
    component: () => import('_views/SearchLists')
  }
]

const router = new VueRouter({
  mode: 'history',
  scrollBehavior (to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else {
      return { x: 0, y: 0 }
    }
  },
  base: process.env.BASE_URL,
  routes
})

// 添加登录鉴权    前置守卫
router.beforeEach((to, from, next) => {
  if (to.meta.needLogin) {
    if (isLogin()) {
      next()
    } else {
      next({
        path: '/login',
        query: {
          from: to.path
        }
      })
    }
  } else {
    next()
  }
})
export default router
